package cn.tannn.ops.sys.service.impl;


import cn.hutool.core.lang.tree.Tree;
import cn.tannn.jdevelops.exception.built.BusinessException;
import cn.tannn.jdevelops.jpa.service.J2ServiceImpl;
import cn.tannn.ops.sys.dao.DictionaryDao;
import cn.tannn.ops.sys.entity.Dictionary;
import cn.tannn.ops.sys.service.DictionaryService;
import cn.tannn.ops.util.TreeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.Comparator;
import java.util.List;

/**
 * 字典表
 *
 * @author tnnn
 * @version V1.0
 * @date 2024-10-9
 */
@Slf4j
@Service
public class DictionaryServiceImpl extends J2ServiceImpl<DictionaryDao, Dictionary, Integer> implements DictionaryService {

    public DictionaryServiceImpl() {
        super(Dictionary.class);
    }


    @Override
    public synchronized String nextCode(String parentCode) {
        if (StringUtils.isBlank(parentCode)) {
            parentCode = "0";
        }
        if (!"0".equals(parentCode)) {
            Dictionary dict = getJpaBasicsDao().findByCode(parentCode)
                    .orElseThrow(() -> new BusinessException("请选择正确的父级"));
            parentCode = dict.getCode();
        }
        List<Dictionary> dictionaries = getJpaBasicsDao().findByParentCode(parentCode);
        if (dictionaries == null || dictionaries.isEmpty()) {
            if ("0".equals(parentCode)) {
                return "100";
            } else {
                return parentCode + "001";
            }
        }
        // asc
        dictionaries.sort(Comparator.comparing(bean -> new BigInteger(bean.getCode())));
        // 获取排序后的最后一个对象
        Dictionary dictionary = dictionaries.get(dictionaries.size() - 1);
        // 将 longString 转为 BigInteger
        BigInteger lastValue = new BigInteger(dictionary.getCode());

        // 对 BigInteger 加一
        BigInteger incrementedValue = lastValue.add(BigInteger.ONE);
        return incrementedValue.toString();
    }

    @Override
    public List<Dictionary> findByParentCode(String parentCode) {
//        return getJpaBasicsDao().findByParentCodeAndAndStatus(parentCode, 1);
        return getJpaBasicsDao().findByParentCode(parentCode, Sort.by("sort").ascending());
    }


    @Override
    public boolean peerUnique(String parentCode, String name) {
        return getJpaBasicsDao().findByParentCodeAndName(parentCode, name).isEmpty();
    }

    @Override
    public void peerUniqueTry(String parentCode, String name) {
        if (!peerUnique(parentCode, name)) {
            throw new BusinessException("同层级不允许出现相同的字典名:" + name);
        }
    }

    @Override
    public void fixSort(Integer id, Integer sort) {
        try {
            getJpaBasicsDao().fixSort(sort, id);
        } catch (Exception e) {
            log.error("修改排序失败，失败Id: {}", id, e);
        }
    }

    @Override
    public List<Dictionary> findEfficacious(String parentCode) {
        if (StringUtils.isNotBlank(parentCode)) {
            return getJpaBasicsDao().findEfficacious(parentCode);
        }
        return getJpaBasicsDao().findEfficacious();
    }

    @Override
    public List<Dictionary> finds(String parentCode) {
        if (StringUtils.isNotBlank(parentCode)) {
            return getJpaBasicsDao().findByParentCode(parentCode, Sort.by("sort").ascending());
        }
        return getJpaBasicsDao().findAll(Sort.by("sort").ascending());

    }

    @Override
    public void enable(String code) {
        getJpaBasicsDao().findByCode(code).ifPresent(exist -> {
            exist.setStatus(1);
            getJpaBasicsDao().save(exist);
            List<Dictionary> dictByParentRLike = getJpaBasicsDao().findLowLevel(code);
            dictByParentRLike.forEach(bean -> {
                bean.setStatus(1);
                getJpaBasicsDao().save(bean);
            });
        });
    }

    @Override
    public void disabled(String code) {
        getJpaBasicsDao().findByCode(code).ifPresent(exist -> {
            exist.setStatus(0);
            getJpaBasicsDao().save(exist);
            List<Dictionary> dictByParentRLike = getJpaBasicsDao().findLowLevel(code);
            dictByParentRLike.forEach(bean -> {
                bean.setStatus(0);
                getJpaBasicsDao().save(bean);
            });
        });
    }

    @Override
    public List<Tree<String>> tree() {
        List<Dictionary> efficacious = getJpaBasicsDao().findEfficacious();
        return TreeUtil.dictTree(efficacious);
    }

}
